package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关 全局过滤器
 *
 * @Author mr.lin
 * @Date 2025/1/24 12:43
 */
@Component
@Order(-1) // 优先级
public class AuthorizeFilter implements GlobalFilter {
    /**
     * 全局过滤器
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象,响应对象,和请求路径
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath(); // 请求路径
        //2.判断是否是登录
        if (!path.contains("/login/login_auth")) {
            //3.校验token
            String token = request.getHeaders().getFirst("token");
            if (token == null) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED); //401
                return response.setComplete();
            }
            //获取payload body信息 就是jwt令牌的完整信息
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claims);
            //-1：有效，0：有效，1：过期，2：过期
            if (i == 1 || i == 2) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED); //401
                return response.setComplete();
            }
        }
        return chain.filter(exchange);
    }
}
